package database

import (
	"fmt"

	"gitee.com/mkwchecking/sr-core/log"
	"gitee.com/mkwchecking/sr-core/storage/database/driver"
	"gorm.io/gorm"
)

func NewGorm(cfg *driver.Config, logger log.Logger) (*gorm.DB, error) {
	fac, ok := driver.GetDriver(cfg.Driver)
	if !ok {
		return nil, fmt.Errorf("driver %s not found", cfg.Driver)
	}

	dial := fac(cfg.Conn)
	db, err := gorm.Open(dial, gormConfig(cfg, logger))
	if err != nil {
		return nil, err
	}

	if resolver, err := driver.MakeResolveRegister(cfg.Resolves...); err == nil {
		db.Use(resolver)
	}

	return db, nil
}
